package com.android.lovingpet.community.teams;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.android.lovingpet.base.BasePresenter;
import com.android.lovingpet.bean.Team;
import com.android.lovingpet.common.Back;
import com.android.lovingpet.common.FileModel;
import com.android.lovingpet.common.UserModel;

import java.util.ArrayList;
import java.util.List;

public class TeamsPresenter extends BasePresenter<TeamsContract.View> implements TeamsContract.Presenter {

    private TeamsModel model = new TeamsModel();

    @Override
    public void getTeams(int offset) {
        if (offset == 0)
            getView().clear();
        model.getTeams(offset, 10, new Back() {
            @Override
            public void onFailure(String msg) {
                getView().complete();
                getView().showToast(msg);
            }

            @Override
            public void onSuccess(@Nullable Bundle bundle) {
                List<Integer> ids = bundle.getIntegerArrayList("ids");
                if (ids == null || ids.isEmpty()) {
                    getView().complete();
                    return;
                }
                getTeam(ids);
            }
        });
    }

    private void getTeam(List<Integer> ids) {
        List<Team> teams = new ArrayList<>();
        for (int i : ids) {
            UserModel.getInstance().getTeamInfo(i, new FileModel.FileBack() {
                private Team team;

                @Override
                public void loadSuccess(String url) {
                    team.setImage(url);
                    teams.add(team);
                    if (teams.size() == ids.size()) {
                        getView().addTeams(teams);
                        getView().complete();
                    }
                }

                @Override
                public void onFailure(String msg) {
                    getView().complete();
                    getView().showToast(msg);
                }

                @Override
                public void onSuccess(@Nullable Bundle bundle) {
                    team = bundle.getParcelable("team");
                }
            });
        }
    }
}
